package cn.amoqi.springboot.redis.subscriptions;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class MessagePublisherImpl implements MessagePublisher {

    private ObjectMapper objectMapper;
    private StringRedisTemplate redisTemplate;

    public MessagePublisherImpl() {
        this.objectMapper = new ObjectMapper()
            .registerModule(new JavaTimeModule())
            .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
            .disable(DeserializationFeature.READ_DATE_TIMESTAMPS_AS_NANOSECONDS)
            .disable(SerializationFeature.WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS);
    }

    @Autowired
    public void setRedisTemplate(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    /**
     * 发送消息
     *
     * @param message
     */
    @Override
    public void send(String message) {
        send("topic", message);
    }

    /**
     * 发送消息
     *
     * @param channel
     * @param message
     */
    @Override
    public void send(String channel, String message) {
        try {
            String messageStr = objectMapper.writeValueAsString(message);
            redisTemplate.convertAndSend(channel, messageStr);
        } catch (JsonProcessingException e) {
            log.error("cannot push message to channel " + channel + ", message: " + message, e);
        }
    }
}